package com.mbyte.easy.admin.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.mbyte.easy.admin.entity.Check;
import com.mbyte.easy.admin.entity.Draft;
import com.mbyte.easy.admin.entity.DraftLog;
import com.mbyte.easy.admin.service.ICheckService;
import com.mbyte.easy.admin.service.IDraftService;
import com.mbyte.easy.common.constant.*;
import com.mbyte.easy.common.controller.BaseController;
import com.mbyte.easy.common.web.AjaxResult;
import com.mbyte.easy.support.es.helper.EsDraftHelper;
import com.mbyte.easy.util.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassNameWriterController
 * @Description 写手发布稿件
 * @Author myr
 * @Date 2019/12/7 13:54
 * @Version 1.0
 **/
@Slf4j
@Controller
@RequestMapping("/draft/writer")
public class WriterController extends BaseController {
    private String prefix = "admin/draft/writer/";

    @Autowired
    private IDraftService draftService;
    @Autowired
    private ICheckService checkService;
    @Autowired
    private EsDraftHelper esDraftHelper;
    @Autowired
    private ApplicationEventPublisher applicationEventPublisher;

    /**
     * 查询登陆写手用户的稿件列表
     * @param model
     * @param pageNo
     * @param pageSize
     * @param draft
     * @return
     */
    @RequestMapping()
    public String index(Boolean isCheck,Model model, @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,
                        String createTimeSpace,Boolean box, Draft draft,
                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize) {
        //box用来判断稿件箱和我的文章搜索框的内容,box为true时有搜索是否通过,false时默认为未审核没有搜索是否通过
        if(box == null){
            box = true;
        }
        if(isCheck == null){
            isCheck = false;
        }
        IPage<Draft> pageInfo = draftService.index(isCheck,false,pageNo,pageSize,draft,createTimeSpace,box);
        setDraftType(model);
        setDraftCheckStatus(model);
        model.addAttribute("code",draft.getStatusCode());
        model.addAttribute("roleId",draftService.selectRoleId());
        model.addAttribute("time",createTimeSpace);
        model.addAttribute("stateDic",StateDic.stateDic());
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", ObjectUtils.isEmpty(pageInfo)?null:new PageInfo(pageInfo));
        model.addAttribute("box",box);
        model.addAttribute("isCheck",isCheck);
        log.info("{}",pageInfo);
        return prefix+"list";
    }


    /**
     * 稿件查重
     * @param text
     * @return
     */
    @RequestMapping("queryByText")
    public String queryByText(Model model,String text){
        model.addAttribute("draftList",draftService.queryByText(text));
        model.addAttribute("text",text);
        setDraftCheckStatus(model);
        model.addAttribute("stateDic",StateDic.stateDic());
        return prefix+"query-text";
    }
    /**
     * 查询登陆写手用户的保存稿件列表
     * @param model
     * @param pageNo
     * @param pageSize
     * @param draft
     * @return
     */
    @RequestMapping("draftBox")
    public String draftBox(Model model, @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,String submitTimeSpace,Boolean box,
                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, Draft draft,String createTimeSpace) {
        if(box == null){
            box = false;
        }
        IPage<Draft> pageInfo = draftService.index(false,true,pageNo,pageSize,draft,createTimeSpace,box);
        setDraftType(model);
        setDraftCheckStatus(model);
        model.addAttribute("roleId",draftService.selectRoleId());
        model.addAttribute("time",createTimeSpace);
        model.addAttribute("stateDic",StateDic.stateDic());
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", new PageInfo(pageInfo));
        model.addAttribute("box",box);
        return prefix+"listno";
    }

    /**
     * 添加跳转页面
     * @return
     */
    @GetMapping("addBefore")
    public String addBefore(Model model){
        long roleId = draftService.selectRoleId();
        model.addAttribute("roleId",roleId);
        setDraftType(model);
        return prefix+"add";
    }
    /**
     * 发布  存稿
     * @param draft
     * @return
     */
    @PostMapping("add")
    @ResponseBody
    public AjaxResult add(Draft draft,String action){
        log.info("action --> {}",action);
        String hitScore = esDraftHelper.getDraftMaxHitScore(draft.getDraftText() + "\n");
        draft.setRepetitiveRate(hitScore);
        return toAjax(draftService.newDraft(draft, action));
    }



    /**
     * 编辑跳转页面
     * @return
     */
    @GetMapping("editBefore/{id}")
    public String editBefore(Model model,@PathVariable("id")Long id){
        Draft draft = draftService.getById(id);
        long roleId = draftService.selectRoleId();
        model.addAttribute("roleId",roleId);
        model.addAttribute("draft",draft);

        setDraftType(model);
        showReason(model,draft);
        //操作日志
        applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_EDIT)
                .setDraftId(draft.getId()));
        return prefix+"edit";
    }

    /**
     * 七队 视频  编辑跳转
     * @param model
     * @param id
     * @return
     */
    @GetMapping("editVideoBefore/{id}")
    public String editVideoBefore(Model model,@PathVariable("id")Long id){
        log.info("==================================");
        Draft draft = draftService.getById(id);
        long roleId = draftService.selectRoleId();
        model.addAttribute("roleId",roleId);
        model.addAttribute("draft",draft);

        setDraftType(model);
        showReason(model,draft);
        return prefix+"edit-video";
    }

    private void showReason(Model model,Draft draft){

        List<Check> checkList = checkService.list(new QueryWrapper<Check>().lambda()
                .eq(Check::getDraftId,draft.getId())
                .eq(Check::getUserId,draft.getLastOperator())
                .orderByDesc(Check::getCreateTime));
        String reason = null;
        if(!CollectionUtils.isEmpty(checkList)){
            reason = checkList.get(0).getReason();
        }
        model.addAttribute("reason",reason);
    }
    /**
     * 操作跳转页面
     * @return
     */
//    @GetMapping("preview/{id}")
//    public String preview(Model model,@PathVariable("id")Long id){
//        Draft draft = draftService.getById(id);
//        model.addAttribute("draft",draft);
//        setDraftType(model);
//        if(draftService.selectRoleId() == SysRole.BLOCK_SEVEN){
//            return prefix+"previewed";
//        }
//        return prefix+"preview";
//    }

    /**
     * 预览跳转页面 7队视频
     * @return
     */
//    @GetMapping("previewVideo/{id}")
//    public String previewVideo(Model model,@PathVariable("id")Long id){
//        Draft draft = draftService.getById(id);
//        model.addAttribute("draft",draft);
//        setDraftType(model);
//        return prefix+"previewvideo";
//    }

    /**
     * 预览跳转页面
     * @return
     */
    @GetMapping("previewlist/{id}")
    public String previewlist(Model model,@PathVariable("id")Long id
            ,String buttonFlag,String checkFlag,String reasonFlag,String agreeFlag,String updateFlag){
        Draft draft = draftService.getById(id);
        model.addAttribute("draft",draft);
        showReason(model,draft);
        setDraftType(model);
        //操作日志
        applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_LOOK)
                .setDraftId(draft.getId()));
        model.addAttribute("agreeFlag",agreeFlag);
        model.addAttribute("buttonFlag",buttonFlag);
        model.addAttribute("checkFlag",checkFlag);
        model.addAttribute("reasonFlag",reasonFlag);
        model.addAttribute("updateFlag",updateFlag);
        return prefix+"previewlist";
    }

    /**
     * 预览跳转页面 7队视频
     * @return
     */
    @GetMapping("previewvideo/{id}")
    public String previewvideo(Model model,@PathVariable("id")Long id
            ,String buttonFlag,String checkFlag,String reasonFlag,String agreeFlag,String updateFlag){
        Draft draft = draftService.getById(id);
        model.addAttribute("draft",draft);
        showReason(model,draft);
        setDraftType(model);
        model.addAttribute("agreeFlag",agreeFlag);
        model.addAttribute("buttonFlag",buttonFlag);
        model.addAttribute("checkFlag",checkFlag);
        model.addAttribute("reasonFlag",reasonFlag);
        model.addAttribute("updateFlag",updateFlag);
        return prefix + "previewvideoed";
    }


    /**
     * 预览跳转页面---6队
     * @return
     */
    @GetMapping("previewlistsix/{id}")
    public String previewlistsix(Model model,@PathVariable("id")Long id
            ,String buttonFlag,String checkFlag,String reasonFlag,String agreeFlag,String updateFlag){
        Draft draft = draftService.getById(id);
        model.addAttribute("draft",draft);
        showReason(model,draft);
        setDraftType(model);
        model.addAttribute("agreeFlag",agreeFlag);
        model.addAttribute("buttonFlag",buttonFlag);
        model.addAttribute("checkFlag",checkFlag);
        model.addAttribute("reasonFlag",reasonFlag);
        model.addAttribute("updateFlag",updateFlag);
            return prefix + "previewlistsix";

    }

    /**
     * 编辑
     * @param draft
     * @return
     */
    @PostMapping("edit")
    @ResponseBody
    public AjaxResult edit(Draft draft, String action){
        draft.setStatusCode(StateDic.Save);
        if (action.equals("submit")){
            draft.setStatusCode(StateDic.Submit);
            //操作日志
            applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_ADD)
                    .setActionContent("重新发布").setDraftId(draft.getId()));
        }else if (action.equals("save")){
            draft.setStatusCode(StateDic.Save);
            //操作日志
            applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.SAVE)
                    .setDraftId(draft.getId()));
        }
        draft.setIsPass(DraftIsPass.NotCheck);
        return toAjax(draftService.update(draft));
    }
    /**
     * 删除
     * @param id
     * @return
     */
    @GetMapping("delete/{id}")
    @ResponseBody
    public AjaxResult delete(@PathVariable("id") Long id){
        return toAjax(draftService.deleteByIds(Arrays.asList(id)));
    }
    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PostMapping("deleteAll")
    @ResponseBody
    public AjaxResult deleteAll(@RequestBody List<Long> ids){
        return toAjax(draftService.deleteByIds(ids));
    }

    /**
     * 稿件类型数据回显
     * @param model
     */
    public void setDraftType(Model model){
        Map<Integer,String> types = new HashMap<Integer,String>();
        types.put(DraftType.Image_Text,"图文");
        types.put(DraftType.QA,"问答");
        types.put(DraftType.PPT,"PPT");
        types.put(DraftType.Audio,"音频");
        types.put(DraftType.VIDEO,"视频稿件");
        types.put(DraftType.WORD,"文字稿件");
        types.put(DraftType.SHORT,"短篇微博问答");
        types.put(DraftType.MID,"中篇微博问答");
        types.put(DraftType.LENGHT,"长篇微博问答");
        types.put(DraftType.ACCOUNTS,"公众号文章");
//        types.put(DraftType.SVIDEO,"视频稿件");
        model.addAttribute("draftTypes",types);
    }

    /**
     * 稿件审核状态回显
     * @param model
     */
    public void setDraftCheckStatus(Model model){
        Map<Integer,String> status = new HashMap<Integer,String>();

        status.put(DraftIsPass.Pass,"已通过");
        status.put(DraftIsPass.NotPass,"未通过");
        status.put(DraftIsPass.NotCheck,"未审核");


        model.addAttribute("draftCheckStatus",status);
    }

    /**
     * 查询登录写手用户视频列表
     */
    @RequestMapping("videoList")
    public String videoList(Boolean isCheck,Model model, @RequestParam(value = "pageNo", required = false, defaultValue = "1") Integer pageNo,String createTimeSpace,Boolean box,
                            @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize, Draft draft) {
        if(box == null){
            box = true;
        }
        if(isCheck == null){
            isCheck = false;
        }
        IPage<Draft> pageInfo = draftService.indexVideo(isCheck,false,pageNo,pageSize,draft,createTimeSpace,box);
        setDraftType(model);
        setDraftCheckStatus(model);
        model.addAttribute("time",createTimeSpace);
        model.addAttribute("stateDic",StateDic.stateDic());
        model.addAttribute("searchInfo", draft);
        model.addAttribute("pageInfo", ObjectUtils.isEmpty(pageInfo)?null:new PageInfo(pageInfo));
        model.addAttribute("box",box);
        model.addAttribute("isCheck",isCheck);
        log.info("{}",pageInfo);
        return prefix + "video-list";
    }

    /**
     * 预览跳转页面 -- 文字
     * @return
     */
    @GetMapping("onlyText/{id}")
    public String onlyText(Model model,@PathVariable("id")Long id
            ,String buttonFlag,String checkFlag,String reasonFlag,String agreeFlag,String updateFlag){
        Draft draft = draftService.getById(id);
        model.addAttribute("draft",draft);
        showReason(model,draft);
        setDraftType(model);
        model.addAttribute("agreeFlag",agreeFlag);
        model.addAttribute("buttonFlag",buttonFlag);
        model.addAttribute("checkFlag",checkFlag);
        model.addAttribute("reasonFlag",reasonFlag);
        model.addAttribute("updateFlag",updateFlag);
        //操作日志
        applicationEventPublisher.publishEvent(new DraftLog().setActionType(DraftLogConstant.ACTION_LOOK)
                .setDraftId(draft.getId()));
        if(draftService.selectRoleId() == SysRole.PARTTIME_SEVEN
                || draftService.selectRoleId() == SysRole.SEVEN_LEADER
                || draftService.selectRoleId() == SysRole.SEVEN_PROOFREADER){
            return prefix + "previewlisted";
        }else if(draftService.selectRoleId() == SysRole.PARTTIME_SIX
                || draftService.selectRoleId() == SysRole.BLOCK_SIX){
            return prefix + "previewlist";
        }
        return prefix+"onlyText";
    }
}
